﻿using KDAcctAttach.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KDAcctAttach {

    public partial class FrmTools : Form {

        public FrmTools()
        {
            InitializeComponent();
        }

        private List<DBItemModel> _dbList;
        private List<KDUserModel> _userList;
        private List<KDConfigModel> _configList;

        #region 启用/禁用界面

        private void EnBtn(bool s)
        {
            void eb()
            {
                //btnRefreshDB.Enabled = s;
                //btnGetAcctConfig.Enabled = s;
                //btnSaveAcctConfig.Enabled = s;
                //btnGetUserList.Enabled = s;
                //btnCleanPass.Enabled = s;
                //btnCleanProfile.Enabled = s;
                plLeft.Enabled = s;
                plRight.Enabled = s;
            }
            if (InvokeRequired)
                Invoke(new MethodInvoker(() => eb()));
            else
                eb();
        }

        #endregion 启用/禁用界面

        #region 窗口载入

        private void FrmTools_Shown(object sender, EventArgs e)
        {
            _dbList = new List<DBItemModel>();
            _userList = new List<KDUserModel>();
            _configList = new List<KDConfigModel>();
            bsDBList.DataSource = _dbList;
            bsUserList.DataSource = _userList;
        }

        #endregion 窗口载入

        #region 刷新列表

        private void BtnRefreshDB_Click(object sender, EventArgs e)
        {
            GetDBList();
        }

        private async void GetDBList()
        {
            try
            {
                EnBtn(false);
                bool kd = rgKDAcct.Checked;
                string sqlstr = "";
                var db = DB.Inst();
                _userList.Clear();
                bsUserList.ResetBindings(false);
                _dbList.Clear();
                bsDBList.ResetBindings(false);
                if (kd)
                {
                    db.ChangeDatabase("AcctCtl");
                    sqlstr = $"select FAcctNumber 'DBName',FAcctName 'DBPath',FVersion 'DBVersion' from t_ad_kdAccount_gl";
                }
                else
                {
                    db.ChangeDatabase("master");
                    sqlstr = $"select name 'DBName' from sysdatabases;";
                }
                var err = await Task.Run(() =>
                {
                    try
                    {
                        var lst = db.Ado.SqlQuery<DBItemModel>(sqlstr);
                        if (lst is null)
                            return null;
                        if (lst.Count < 1)
                            return null;
                        _dbList.AddRange(lst);
                        return null;
                    }
                    catch (Exception ex)
                    {
                        return ex.Message;
                    }
                });
                if (!string.IsNullOrEmpty(err))
                    throw new Exception(err);
                bsDBList.ResetBindings(false);
                EnBtn(true);
            }
            catch (Exception ex)
            {
                EnBtn(true);
                MessageBox.Show(ex.Message);
            }
        }

        #endregion 刷新列表

        #region 查询用户列表

        private void BtnGetUserList_Click(object sender, EventArgs e)
        {
            try
            {
                string dbname = GetSelectedAcct();
                var db = DB.Inst();
                if (!db.IsAnyConnection(dbname))
                    DB.GetConn(db, dbname);
                _userList.Clear();
                bsUserList.ResetBindings(false);
                var lst = db.Ado.SqlQuery<KDUserModel>("select FUserID, FName, FDescription from t_user");
                if (lst is null)
                    return;
                if (lst.Count < 1)
                    return;
                _userList.AddRange(lst);
                bsUserList.ResetBindings(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private string GetSelectedAcct()
        {
            if (dgvAcctList.SelectedRows.Count < 1)
                throw new Exception("必须选择账套");
            string dbname = dgvAcctList.Rows[dgvAcctList.SelectedRows[0].Index].Cells[0].Value.ToString();
            return dbname;
        }

        #endregion 查询用户列表
        #region 清密码
        private void BtnCleanPass_Click(object sender, EventArgs e)
        {
            try
            {
                string dbName = GetSelectedAcct();
                int userId = GetSelectedUserId();
                if (MessageBox.Show("是否确认要清空当前选择用户的密码?", "清空密码", MessageBoxButtons.YesNo) != DialogResult.Yes)
                    return;
                var db = DB.Inst();
                DB.GetConn(db, dbName);
                db.Ado.ExecuteCommand($"update t_user set FSID=null where FUserID={userId};");
                MessageBox.Show("OK");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        #region 获取当前选择的用户
        private int GetSelectedUserId()
        {
            if (dgvUserList.SelectedRows.Count < 1)
                throw new Exception("必须选择用户");
            int userId = Convert.ToInt32(dgvUserList.Rows[dgvUserList.SelectedRows[0].Index].Cells[0].Value);
            if (userId <= 0)
                throw new Exception("当前用户不能执行此操作");
            return userId;
        }
        #endregion
        #region 清配置
        private void BtnCleanProfile_Click(object sender, EventArgs e)
        {
            try
            {
                string dbName = GetSelectedAcct();
                int userId = GetSelectedUserId();
                if (MessageBox.Show("是否确认要清除选中用户的配置信息?", "清除配置", MessageBoxButtons.YesNo) != DialogResult.Yes)
                    return;
                var db = DB.Inst();
                DB.GetConn(db,dbName);
                db.Ado.ExecuteCommand($"delete t_userProfile where FUserID={userId};");
                MessageBox.Show("OK");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        #region 读取参数
        private void BtnGetAcctConfig_Click(object sender, EventArgs e)
        {
            try
            {
                string dbName = GetSelectedAcct();
                var db = DB.Inst();
                DB.GetConn(db, dbName);
                _configList = db.Ado.SqlQuery<KDConfigModel>("select FKey,FValue,FCategory from t_SystemProfile;");
                SetConfigControls();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        #region 设置参数控件
        private void SetConfigControls()
        {
            // 核算方式
            var config = GetConfig("IC", "CalculateType");
            if (config != null)
            {
                rgCalculateType0.Checked = !Comm.ToBool(config.FValue);
                rgCalculateType1.Checked = Comm.ToBool(config.FValue);
            }
            // 批号手工修改
            config = GetConfig("IC", "BatchManual");
            if (config != null)
                chkBatchManual.Checked = Comm.ToBool(config.FValue);
            // 批号重复给出提示
            config = GetConfig("IC", "BatchRepeatEcho");
            if (config != null)
                chkBatchRepeatEcho.Checked = Comm.ToBool(config.FValue);
            // 采购订单执行数量允许超过订单量
            config = GetConfig("IC", "CQtyLargePOQty");
            if (config != null)
                chkCQtyLargePOQty.Checked = Comm.ToBool(config.FValue);
            // 销售订单执行数量允许超过订单量
            config = GetConfig("IC", "CQtyLargeSEQty");
            if (config != null)
                chkCQtyLargeSEQty.Checked = Comm.ToBool(config.FValue);
            // 暂估冲回方式
            config = GetConfig("IC", "InInvProcess");
            if(config != null)
            {
                rgInInvProcess0.Checked = !Comm.ToBool(config.FValue);
                rgInInvProcess1.Checked = Comm.ToBool(config.FValue);
            }
            // 存货计价方法
            config = GetConfig("IC", "ItemCountPrice");
            if(config != null)
            {
                rgItemCountPrice0.Checked = !Comm.ToBool(config.FValue);
                rgItemCountPrice1.Checked = Comm.ToBool(config.FValue);
            }
            // 采购发票和入库单数量不致不允许勾稽
            config = GetConfig("IC", "NoHookPIWhenDiffQty");
            if (config != null)
                chkNoHookPIWhenDiffQty.Checked = Comm.ToBool(config.FValue);
            // 销售发票和出库单数量不一致不允许勾稽
            config = GetConfig("IC", "NoHookSIWhenDiffQty");
            if (config != null)
                chkNoHookSIWhenDiffQty.Checked = Comm.ToBool(config.FValue);
            // 采购单价与蓝字采购发票价格同步
            config = GetConfig("IC", "PoInvSynInPrice");
            if (config != null)
                chkPoInvSynInPrice.Checked = Comm.ToBool(config.FValue);
            // 已关闭的采购订单可以追加物料
            config = GetConfig("IC", "POOrderCanAppendItem");
            if (config != null)
                chkPOOrderCanAppenItem.Checked = Comm.ToBool(config.FValue);
            // 已关闭的销售订单可以追加物料
            config = GetConfig("IC", "SEOrderCanAppendItem");
            if (config != null)
                chkSEOrderCanAppenItem.Checked = Comm.ToBool(config.FValue);
            // 采购订单单价默认为含税
            config = GetConfig("IC", "POrderTaxInPrice");
            if (config != null)
                chkPOrderTaxInPrice.Checked = Comm.ToBool(config.FValue);
            // 序时簿新增后立即刷新
            config = GetConfig("IC", "RefreshAfterAdd");
            if (config != null)
                chkRefreshAfterAdd.Checked = Comm.ToBool(config.FValue);
            // 反审核与审核为同一人
            config = GetConfig("IC", "SameUserApprovalAndUnApproval");
            if (config != null)
                chkSameUserApprovalAndUnApproval.Checked = (Comm.ToBool(config.FValue));
            // 允许负库存出库
            config = GetConfig("IC", "UnderStock");
            if (config != null)
                chkUnderStock.Checked = Comm.ToBool(config.FValue);
            // 允许负库存结账
            config = GetConfig("IC", "UnderStockCalculate");
            if (config != null)
                chkUnderStockCalculate.Checked = Comm.ToBool(config.FValue);

            // 库存更新控制
            config = GetConfig("IC", "UPSTOCKWHENSAVE");
            if(config != null)
            {
                rgUPSTOCKWHENSAVE0.Checked = !Comm.ToBool(config.FValue);
                rgUPSTOCKWHENSAVE1.Checked = Comm.ToBool(config.FValue);
            }
            // 任务单确认时自动下达
            config = GetConfig("SH", "ICMOCONFIRM_RELEASE");
            if (config != null)
                chkICMOCONFIRM_RELEASE.Checked = Comm.ToBool(config.FValue);
            // 任务汇报审核时自动生成生产物料报废单
            config = GetConfig("SH", "ICMORptAutoBuildItemScrap");
            if (config != null)
                chkICMORptAutoBuildItemScrap.Checked = Comm.ToBool(config.FValue);
            // 计件工资清单放开1000行限制
            config = GetConfig("SH","JOBPAY_NOTCONTROLMAXROW");
            if (config != null)
                chkJOBPAY_NOTCONTROLMAXROW.Checked = Comm.ToBool(config.FValue);
        }
        private KDConfigModel GetConfig(string category, string name)
        {
            return _configList.FirstOrDefault(p => p.FKey == name && p.FCategory == category);
        }
        #endregion
        #region 保存参数
        private void BtnSaveAcctConfig_Click(object sender, EventArgs e)
        {
            try
            {
                string dbName = GetSelectedAcct();
                if (MessageBox.Show("是否确认要保存参数?", "保存参数", MessageBoxButtons.YesNo) != DialogResult.Yes)
                    return;
                string sqlstr = "";
                // 核算方式
                bool val = rgCalculateType1.Checked;
                sqlstr += GenSql("IC", "CalculateType", val);
                // 批号手工修改
                sqlstr += GenSql("IC", "BatchManual", chkBatchManual.Checked);
                // 批号重复给出提示
                sqlstr += GenSql("IC", "BatchRepeatEcho",chkBatchRepeatEcho.Checked);
                // 采购订单执行数量允许超过订单量
                sqlstr += GenSql("IC", "CQtyLargePOQty",chkCQtyLargePOQty.Checked);
                // 销售订单执行数量允许超过订单量
                sqlstr += GenSql("IC", "CQtyLargeSEQty",chkCQtyLargeSEQty.Checked);
                // 暂估冲回方式
                sqlstr += GenSql("IC", "InInvProcess",rgInInvProcess1.Checked);
                // 存货计价方法
                sqlstr += GenSql("IC", "ItemCountPrice", rgItemCountPrice1.Checked);
                // 采购发票和入库单数量不致不允许勾稽
                sqlstr += GenSql("IC", "NoHookPIWhenDiffQty", chkNoHookPIWhenDiffQty.Checked);

                // 销售发票和出库单数量不一致不允许勾稽
                sqlstr += GenSql("IC", "NoHookSIWhenDiffQty", chkNoHookSIWhenDiffQty.Checked);
                // 采购单价与蓝字采购发票价格同步
                sqlstr += GenSql("IC", "PoInvSynInPrice", chkPoInvSynInPrice.Checked);
                // 已关闭的采购订单可以追加物料
                sqlstr += GenSql("IC", "POOrderCanAppendItem", chkPOOrderCanAppenItem.Checked);
                // 已关闭的销售订单可以追加物料
                sqlstr += GenSql("IC", "SEOrderCanAppendItem", chkSEOrderCanAppenItem.Checked);
                // 采购订单单价默认为含税
                sqlstr += GenSql("IC", "POrderTaxInPrice", chkPOrderTaxInPrice.Checked);
                // 序时簿新增后立即刷新
                sqlstr += GenSql("IC", "RefreshAfterAdd", chkRefreshAfterAdd.Checked);
                // 反审核与审核为同一人
                sqlstr += GenSql("IC", "SameUserApprovalAndUnApproval", chkSameUserApprovalAndUnApproval.Checked);
                // 允许负库存出库
                sqlstr += GenSql("IC", "UnderStock", chkUnderStock.Checked);
                // 允许负库存结账
                sqlstr += GenSql("IC", "UnderStockCalculate", chkUnderStockCalculate.Checked);
                // 库存更新控制
                sqlstr += GenSql("IC", "UPSTOCKWHENSAVE", rgUPSTOCKWHENSAVE1.Checked);
                
                // 任务单确认时自动下达
                sqlstr += GenSql("SH", "ICMOCONFIRM_RELEASE", chkICMOCONFIRM_RELEASE.Checked);
                // 任务汇报审核时自动生成生产物料报废单
                sqlstr += GenSql("SH", "ICMORptAutoBuildItemScrap", chkICMORptAutoBuildItemScrap.Checked);
                // 计件工资清单放开1000行限制
                sqlstr += GenSql("SH", "JOBPAY_NOTCONTROLMAXROW", chkJOBPAY_NOTCONTROLMAXROW.Checked);
                var db = DB.Inst();
                DB.GetConn(db, dbName);
                db.Ado.ExecuteCommand(sqlstr);
                MessageBox.Show("OK");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private string GenSql(string cate,string name, bool val)
        {
            string value = Comm.ToInt(val).ToString();
            string sqlstr = $"Update t_SystemProfile set FValue={value} where FCategory='{cate}' and FKey='{name}';";
            return sqlstr;
        }
        #endregion
    }
}